import { Breadcrumb, Button, Card, Form, message, Modal, Input, Popconfirm, Space, Table, Tag, Tooltip, Cascader } from 'antd'
import React, { Component } from 'react'
import { addCategory, deleteCategory, editCategory, getCategories } from '../../../api/goods'
import {CheckCircleTwoTone, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import "./index.css"
export default class GoodsCategory extends Component {
  state = {
    addCateModalVisiable:false,
    editCateModalVisiable:false,
    total:0,
    editCateId:null,
    cascaderOptions:{
      label:"cat_name",
      value:"cat_id"
    },
    cateColumns:[
      {
        title:"分类名称",
        dataIndex:"cat_name",
        key:"cat_name",
        align:"center"
      },
      {
        title:"是否有效",
        dataIndex:"cat_deleted",
        key:"cat_deleted",
        align:"center",
        render: (text,record,index) => {
          if(!record.cat_deleted){
            return <CheckCircleTwoTone twoToneColor="#52c41a" />
          }else{
            return <p>失败</p>
          }
        }
      },
      {
        title:"分类级别",
        dataIndex:"cat_level",
        key:"cat_level",
        align:"center",
        render: (text,record) => {
          switch(record.cat_level){
            case 0:return <Tag color="blue">一级</Tag>;
            case 1:return <Tag color="success">二级</Tag>;
            case 2:return <Tag color="orange">三级</Tag>
            default: return <Tag>error</Tag>
          }
        }
      },
      {
        title:"操作",
        align:"center",
        render: (text,record) => {
          return (
            <Space>
              <Tooltip title="编辑此分类">
                <Button type="primary" icon={<EditOutlined />} onClick={_=>this.showEditCateModal(record)}></Button>
              </Tooltip>
              <Popconfirm
                title="确定删除此分类吗？"
                onConfirm={_=>this.delCate(record.cat_id)}
              >
                <Button type="danger" icon={<DeleteOutlined />}/>
              </Popconfirm>
            </Space>
          )
        }
      }
    ],
    cateList:[],
    pagesize:10,
    pagenum:1,
  }
  getCateList = async ()=>{
    const res = await getCategories(3,this.state.pagenum,this.state.pagesize);
    if(res.meta.status!==200){
      message.error(res.meta.msg)
    }else{
      this.setState({
        cateList:res.data.result,
        total:res.data.total
      })
    }
  }
  showAddCateModal = ()=>{
    this.setState({
      addCateModalVisiable:true,
    })
  }
  handleCancelAddCate = ()=>{
    this.refs.addCateFormRef.resetFields()
    this.setState({
      addCateModalVisiable:false,
    })
  }
  handleOKAddCate = () => {
    this.refs.addCateFormRef.submit()
  }
  onFinishAddCate = async (values)=>{
    const {cat_name,cat_pid} = values;
    let pid = 0,cat_level=0;
    if(!cat_pid){
      pid = 0;
      cat_level = 0;
    }else{
      const n = cat_pid.length
      cat_level = n >=2? 2:cat_pid.length;
      pid = n>=2? cat_pid[1]:cat_pid[0];
    }
    const res = await addCategory(cat_name,cat_level,pid);
    if(res.meta.status !== 201){
      message.error(res.meta.msg)
    }else{
      message.success(res.meta.msg)
      this.getCateList();
    }
    this.handleCancelAddCate()
  }
  onFinishAddCateFailed = ()=>{
    message.error("请填写完整表单数据再提交")
  }
  delCate =async (id)=>{
    const res = await deleteCategory(id);
    if(res.meta.status === 200){
      message.success(res.meta.msg)
      this.getCateList();
    }else{
      message.error(res.meta.msg)
    }
  }
  showEditCateModal = async (record)=>{
    await this.setState({
      editCateModalVisiable:true,
      editCateId:record.cat_id,
    })
    this.refs.editCateFormRef.setFieldsValue({
      ["oldName"]:record.cat_name
    })
  }
  handleCancelEditCate = ()=>{
    this.refs.editCateFormRef.resetFields()
    this.setState({
      editCateModalVisiable:false,
      editCateId:null,
    })
  }
  handleOKEditCate = () => {
    this.refs.editCateFormRef.submit();
  }
  onFinishEditCate = async (values) => {
    const {newName} = values;
    const res = await editCategory(this.state.editCateId,newName)
    if(res.meta.status===200){
      message.success(res.meta.msg)
      this.getCateList()
    }else{
      message.error(res.meta.msg)
    }
    this.handleCancelEditCate()
  }
  onFinishEditCateFailed = ()=>{
    message.error("请填写完表单再提交")
  }
  componentDidMount(){
    this.getCateList()
  }
  render() {
    return (
      <div>
        <Card>
          <Breadcrumb className="bread">
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>商品管理</Breadcrumb.Item>
            <Breadcrumb.Item>商品分类</Breadcrumb.Item>
          </Breadcrumb>
          <Button type="primary" onClick={this.showAddCateModal}>添加分类</Button>
          <Table
            rowKey="cat_id"
            className="table"
            dataSource={this.state.cateList}
            bordered
            pagination={{
              current:this.state.pagenum,
              total:this.state.total,
              pageSize:this.state.pagesize,
              pageSizeOptions:['5','10','15','20'],
              showSizeChanger:true,
              showQuickJumper:true,
              showTotal: (total, range) => {return`当前范围：${range[0]}-${range[1]};总数：${total}`},
              onChange: async (page,pagesize)=>{
                await this.setState({
                  pagenum:page,
                  pagesize
                })
                this.getCateList();
              }
            }}
            columns={this.state.cateColumns}
          >
          </Table>
        </Card>
        <Modal 
          title="添加分类" 
          visible={this.state.addCateModalVisiable}
          onCancel={this.handleCancelAddCate}
          onOk={this.handleOKAddCate}
        >
          <Form 
            ref="addCateFormRef"
            labelCol={{span:4}}
            labelAlign='right'
            onFinish={this.onFinishAddCate}
            onFinishFailed={this.onFinishAddCateFailed}
          >
            <Form.Item label="分类名称" name="cat_name" rules={[{required:true,message:"请填写分类名称"}]}>
              <Input/>
            </Form.Item>
            <Form.Item label="父类名称" name="cat_pid">
            <Cascader
              options={this.state.cateList}
              fieldNames={this.state.cascaderOptions}
              changeOnSelect
              placeholder="请选择父类，如果不选择则默认添加1级分类"
              showSearch={true}
            />
            </Form.Item>
          </Form>
        </Modal>
        <Modal 
          title="编辑分类" 
          visible={this.state.editCateModalVisiable}
          onCancel={this.handleCancelEditCate}
          onOk={this.handleOKEditCate}
        >
          <Form 
            ref="editCateFormRef"
            labelCol={{span:4}}
            labelAlign='right'
            onFinish={this.onFinishEditCate}
            onFinishFailed={this.onFinishEditCateFailed}
          >
            <Form.Item label="原分类名" name="oldName">
              <Input/>
            </Form.Item>
            <Form.Item label="新分类名" name="newName" rules={[{required:true,message:"请填写新名称"}]}>
              <Input/>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
